<template>
  <div class="store-info">
    <el-form ref="dataForm" :model="store" :rules="rules" label-width="100px" style="padding-right: 40px">
      <el-form-item label="门店名" prop="storeName" style="width: 400px">
        <el-input v-model="store.storeName" />
      </el-form-item>
      <el-form-item label="门店电话" prop="phone" style="width: 400px">
        <el-input v-model="store.phone" />
      </el-form-item>

      <el-form-item label="城市" prop="city">
        <el-cascader v-model="city" size="large" :options="pcTextArr" @change="selectCity" />
      </el-form-item>
      <el-form-item label="详细地址" prop="address" style="width: 700px" >
        <el-input v-model="store.address"
                  placeholder="例：北京市大兴区新源大街与华佗路交汇处天宫o院凯德F6-05B古德菲力健身"/>
      </el-form-item>

      <el-form-item label="门店标签" prop="label" style="width: 700px">
        <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
                @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
        <el-input v-if="inputVisible" ref="saveTagInput" v-model="inputValue" class="input-new-tag" size="small"
                  @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
      </el-form-item>
      <el-form-item label="缩略图" prop="thumbnail">
        <el-upload class="avatar-uploader" action="/dev-api/admin/common/upload" :show-file-list="false"
                   :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="store.thumbnail" :src="store.thumbnail" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="轮播图" prop="banner">
        <el-upload action="/dev-api/admin/common/upload" list-type="picture-card" :file-list="store.banner"
                   :on-success="handleAvatarSuccess2" :on-preview="handlePictureCardPreview"
                   :on-remove="handleRemove2">
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="门店详情" prop="detail">
        <tinymce v-model="store.details" :height="300" />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
            <el-button size="small" icon="el-icon-refresh-right" @click="cancel">取 消</el-button>
            <el-button type="primary" icon="el-icon-check" size="small"
                       @click="saveOrUpdate('dataForm')">确
                定</el-button>
        </span>
  </div>
</template>
<!-- 引入百度地图的JavaScript API -->
//
<script>
import { pcTextArr } from "element-china-area-data";
import Tinymce from "@/components/Tinymce";
import api from "@/api/content/store";
import BMapGL from "vue-baidu-map";
const defaultForm = {
  id: "",
  storeName: "",
  phone: "",
  city: "",
  address: "",
  latitude: "",
  longitude: "",
  label: "",
  details: "",
  thumbnail:'',
  banner: [],
};

export default {
  components: { Tinymce },
  data() {
    return {
      pcTextArr,
      city: [],
      store: defaultForm,
      point: null,

      dynamicTags: [],
      inputVisible: false,
      inputValue: '',

      // 上传轮播图
      dialogVisible: false,
      dialogImageUrl: '',

      rules: {
        storeName: [
          { required: true, message: "请填写门店名", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请填写电话", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
        city: [{ required: true, message: "请选择城市", trigger: "change" }],
        address: [
          { required: true, message: "请填写详细地址", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    console.log(this.$route.query.id);
    if (!this.$route.query.id) {
      this.store = defaultForm;
    } else {
      this.fetchData(this.$route.query.id);
    }
  },
  methods: {
    fetchData(id) {
      api.getById(id).then((response) => {
        this.store = response.data;
        this.city = this.store.city.split("/");
        this.dynamicTags = this.store.label.split("/");
      });
    },
    //添加或更新
    saveOrUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.store.label = this.dynamicTags.join("/");
          if (!this.store.id) {
            this.save(formName);
          } else {
            this.update(formName);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加
    save() {
      api.save(this.store).then((response) => {
        this.$message.success(response.message || "操作成功");
        this.$router.replace("/content/store");
      });
    },
    //更新
    update(formName) {
      api.updateById(this.store).then((response) => {
        this.$message.success(response.message || "操作成功");
        this.$router.replace("/content/store");
      });
    },

    //选择城市
    selectCity(val) {
      this.store.city = val[0] + "/" + val[1];
    },
    //取消
    cancel() {
      this.$router.go(-1);
    },

    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    // 上传轮播图
    handleAvatarSuccess2(response, file, fileList) {
      fileList[fileList.length - 1] = {
        name: file.name,
        url: response.data
      }
      this.store.banner = fileList
    },
    handleRemove2(file, fileList) {
      this.store.banner = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 上传图片成功
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.store.thumbnail = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
  }
}
</script>

<style lang="scss" scoped>
.store-info {
  margin: 30px;
  margin-top: 40px;

  .dialog-footer {
    margin-left: 40px;
    margin-bottom: 20px;
  }
}
</style>

<style scoped>
.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
